<template>
	<view class="container">
		<u--form
			labelPosition="left"
			:rules="rules"
			:model="form"
			ref="form">
			<u-form-item
				label="旧密码"
				prop="oldPassword"
				labelWidth="70"
				borderBottom>
				<u--input type="password" v-model="form.oldPassword" border="none"/>
			</u-form-item>
			<u-form-item
				label="新密码"
				prop="newPassword"
				labelWidth="70"
				borderBottom>
				<u--input type="password" v-model="form.newPassword" border="none"/>
			</u-form-item>
			<u-form-item
				label="确认密码"
				prop="confirmPassword"
				labelWidth="70"
				borderBottom>
				<u--input type="password" v-model="form.confirmPassword" border="none"/>
			</u-form-item>
		</u--form>
		<button class="update-button" @click="update">修改</button>
	</view>
</template>
<script>
import md5 from 'js-md5';
export default {
	data() {
		return {
			form: {
				// 旧密码
				oldPassword: null,
				// 新密码
				newPassword: null,
				// 确认密码
				confirmPassword: null,
				// 原始密码
				password: null
			},
			rules: {
				oldPassword: [{
					required: true,
					message: '请输入旧密码'
				}, {
					validator: (rule, value) => md5(value) === this.password,
					message: '旧密码不正确'
				}],
				newPassword: {
					required: true,
					message: '请输入新密码'
				},
				confirmPassword: [{
					required: true,
					message: '请确认密码'
				}, {
					validator: (rule, value) => value === this.form.newPassword,
					message: '密码不一致',
				}]
			}
		};
	},
	created() {
		// 获取原始密码
		this.password = uni.getStorageSync('password');
	},
	methods: {
		/**
		 * 修改按钮
		 */
		async update() {
			// 表单校验
			await this.$refs.form.validate();

			// 进行修改密码
			uni.setStorageSync('password', md5(this.form.newPassword));
			uni.navigateBack();

			// 成功提示
			uni.$emit('settingSuccess', '修改成功');
		}
	}
}
</script>
<style scoped>
.container {
	padding: 10px;
}
.update-button {
	width: 100%;
	height: 40px;
	line-height: 40px;
	border-radius: 20px;
	background-color: #409EFF;
	color: white;
	margin: 15px 0;
}
</style>
